import { useEffect, useState } from "react";
import { unstable_usePrompt } from "react-router-dom";
import { DeleteOutlined, LoadingOutlined, MinusOutlined, PlusOutlined } from "@ant-design/icons";
import { Button, DatePicker, Flex, Form, Image, Input, InputNumber, Select, Upload } from "antd";
import type { FormInstance, GetProp, UploadFile, UploadProps } from "antd/";
import dayjs from "dayjs";
import type { Values } from "../types";
import { getUploadFileToken, uploadFile } from "@/api";
import {
  ORDER_CONTENT_CATEGORY_OPTIONS,
  ORDER_CONTENT_TYPE_OPTIONS,
  ORDER_STATUS_OPTIONS,
  PLATFORM_OPTIONS,
} from "@/constants/options";

interface EditFormProps {
  initialValues?: Values;
  onFormInstanceReady: (instance: FormInstance<Values>) => void;
  onSubmit: () => void;
  onReset: () => void;
}

type FileType = Parameters<GetProp<UploadProps, "beforeUpload">>[0];

export default function EditForm({ initialValues, onFormInstanceReady, onReset, onSubmit }: EditFormProps) {
  const [form] = Form.useForm();
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [previewImage, setPreviewImage] = useState("");
  const [hasChanged, setHasChanged] = useState(false);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    onFormInstanceReady(form);
    if (initialValues) {
      console.log("initialValues: ", initialValues);
      const formValues = {
        ...initialValues,
        applyDeadline: dayjs(initialValues.applyDeadline),
        cooperationDate: [dayjs(initialValues.cooperationStart), dayjs(initialValues.cooperationEnd)],
      };
      setPreviewImage(initialValues.coverImage);
      setFileList([
        {
          uid: "-1",
          name: initialValues.coverImage,
          url: initialValues.coverImage,
        },
      ]);
      form.setFieldsValue(formValues);
    } else {
      form.setFieldsValue({
        platform: "xhs",
        isVisible: false,
      });
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [initialValues]);

  // https://reactrouter.com/en/main/hooks/use-prompt
  // Block navigating elsewhere when data has been entered into the input
  unstable_usePrompt({
    message: "您还有未保存的修改，确定要离开吗？",
    when: ({ currentLocation, nextLocation }) =>
      hasChanged && currentLocation.pathname !== nextLocation.pathname,
  });

  const beforeUpload = (file: FileType) => {
    const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
    if (!isJpgOrPng) {
      window.$message?.error("You can only upload JPG/PNG file!");
    }
    const limit = file.size / 1024 / 1024 < 5;
    if (!limit) {
      window.$message?.error("图片大小不能超过5MB!");
    }
    return isJpgOrPng && limit;
  };

  const validateFieldsOptions = {
    title: [{ required: true, message: "请输入商单标题" }],
    brand: [{ required: true, message: "请输入合作品牌" }],
    influencerCount: [{ required: true, message: "请输入达人需求" }],
    contentType: [{ required: true, message: "请选择合作类型" }],
    contentCategory: [{ required: true, message: "请选择内容领域" }],
    fansMin: [{ required: true, message: "请输入粉丝数量" }],
    fansMax: [{ required: true, message: "请输入粉丝数量" }],
    cooperationDate: [{ required: true, message: "请选择合作档期" }],
    applyDeadline: [{ required: true, message: "请选择报名截止时间" }],
    feeDescription: [{ required: true, message: "请输入稿费说明" }],
    coverImage: [{ required: true, message: "请上传图片" }],
    isVisible: [{ required: true, message: "请选择商单状态" }],
    details: [{ required: true, message: "请输入内容描述" }],
  };

  const customRequest = async (options: any) => {
    console.log("customRequest: ", options);
    setLoading(true);
    setFileList([...fileList, options.file]);
    const data = {
      fileName: options.file.name,
      fileType: options.file.type,
      requestMethod: "PUT",
    };
    try {
      const { token, key } = await getUploadFileToken(data);
      if (token && key) {
        const { url } = await uploadFile(options.file, key, token, options.file.type);
        if (url) {
          setPreviewImage(url);
          form.setFieldsValue({
            coverImage: url,
          });
        }
      }
    } catch (error) {
      console.log("error: ", error);
      window.$message?.error("上传失败");
      setFileList([]);
      setPreviewImage("");
      form.setFieldsValue({
        coverImage: "",
      });
    } finally {
      setLoading(false);
    }
  };

  const handleDeleteCoverImage = (e: React.MouseEvent<HTMLButtonElement>) => {
    e.preventDefault();
    e.stopPropagation();
    setFileList([]);
    setPreviewImage("");
    form.setFieldsValue({
      coverImage: "",
    });
  };

  return (
    <Form
      layout="horizontal"
      form={form}
      name="form_in_modal"
      // initialValues={initialValues ? initialValues : { platform: "xhs" }}
      preserve={false}
      labelAlign="right"
      onValuesChange={() => {
        console.log("onValuesChange");
        setHasChanged(true);
      }}
      onReset={() => {
        onReset();
        form.resetFields();
        form.setFieldsValue({
          platform: "xhs",
          isVisible: false,
        });
      }}
      onFinish={() => {
        console.log("onFinish");
        onSubmit();
      }}
      labelCol={{ flex: "120px" }}
      wrapperCol={{ flex: 1 }}
      className="mt-4 w-5/6"
    >
      <Form.Item name="title" label="商单标题" rules={validateFieldsOptions.title}>
        <Input maxLength={20} showCount />
      </Form.Item>
      <Form.Item name="platform" label="平台">
        <Select options={PLATFORM_OPTIONS} disabled variant="borderless" />
        {/* <Select options={PLATFORM_OPTIONS} /> */}
      </Form.Item>
      <Form.Item name="brand" label="合作品牌" rules={validateFieldsOptions.brand}>
        <Input />
      </Form.Item>
      <Form.Item name="influencerCount" label="达人需求" rules={validateFieldsOptions.influencerCount}>
        <InputNumber />
      </Form.Item>
      <Form.Item name="contentCategory" label="内容领域" rules={validateFieldsOptions.contentCategory}>
        <Select options={ORDER_CONTENT_CATEGORY_OPTIONS} showSearch />
      </Form.Item>
      <Form.Item name="contentType" label="合作类型" rules={validateFieldsOptions.contentType}>
        <Select options={ORDER_CONTENT_TYPE_OPTIONS} />
      </Form.Item>
      <Form.Item label="粉丝数量" required>
        <Flex align="center">
          <Form.Item name="fansMin" className="m-0 w-32" rules={validateFieldsOptions.fansMin}>
            <InputNumber style={{ width: "100%" }} min={0} controls={false} suffix="K" />
          </Form.Item>
          <MinusOutlined />
          <Form.Item name="fansMax" className="m-0 w-32" rules={validateFieldsOptions.fansMax}>
            <InputNumber style={{ width: "100%" }} min={0} controls={false} suffix="K" />
          </Form.Item>
        </Flex>
      </Form.Item>
      <Form.Item name="cooperationDate" label="合作档期" rules={validateFieldsOptions.cooperationDate}>
        <DatePicker.RangePicker />
      </Form.Item>
      <Form.Item name="feeDescription" label="稿费说明" rules={validateFieldsOptions.feeDescription}>
        <Input maxLength={50} showCount />
      </Form.Item>
      <Form.Item name="applyDeadline" label="报名截止时间" rules={validateFieldsOptions.applyDeadline}>
        <DatePicker />
      </Form.Item>
      <Form.Item name="coverImage" label="展示附图" rules={validateFieldsOptions.coverImage}>
        <Upload
          fileList={fileList}
          beforeUpload={beforeUpload}
          showUploadList={false}
          customRequest={customRequest}
          accept=".png,.jpg,.bmp"
        >
          {previewImage !== "" ? (
            <div className="w-40 relative flex" onClick={(e) => e.stopPropagation()}>
              <Image src={previewImage || ""} preview={false} className="w-full" />
              <div className="absolute flex justify-center items-center w-full h-full left-0 top-0 opacity-0 hover:bg-slate-950/10 hover:opacity-100 transition-all duration-200">
                <Button type="text" onClick={handleDeleteCoverImage}>
                  <DeleteOutlined className="hover:text-gray-300 transition-all duration-200" />
                </Button>
              </div>
            </div>
          ) : (
            <>
              <Flex justify="center" gap={10}>
                <div className="w-40 h-32 bg-gray-300 cursor-pointer flex items-center justify-center">
                  {loading ? <LoadingOutlined className="text-2xl" /> : <PlusOutlined className="text-2xl" />}
                </div>
                <div className="flex flex-col justify-end text-sm text-gray-400">
                  <p>请上传图片</p>
                  <p>支持jpg/png/bmp格式</p>
                  <p>文件5MB以内</p>
                </div>
              </Flex>
            </>
          )}
        </Upload>
      </Form.Item>
      <Form.Item name="isVisible" label="商单状态" rules={validateFieldsOptions.isVisible}>
        <Select options={ORDER_STATUS_OPTIONS} />
      </Form.Item>
      <Form.Item name="details" label="内容描述" rules={validateFieldsOptions.details}>
        <Input.TextArea maxLength={500} showCount placeholder="请输入" rows={4} />
      </Form.Item>
      <Form.Item label={null}>
        <Flex gap={40} justify="center">
          <Button type="default" htmlType="reset">
            重置
          </Button>
          <Button type="primary" htmlType="submit">
            提交
          </Button>
        </Flex>
      </Form.Item>
    </Form>
  );
}
